package com.ionehe.cola.config;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域过滤器
 *
 * @author 2022/1/24 <a href="mailto:a@ionehe.com">skedison</a>
 */
@Order(-1)
@Component
@WebFilter(filterName = "jsonPFilter", urlPatterns = {"/*"})
public class CrossOriginFilter implements Filter {
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse servletResponse,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Version,User-agent,Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X_TIMESTAMP, X_NONCE, X_EAK, X_SIGN");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //对于OPTIONS的请求放行
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig cfg) throws ServletException {

    }
}
